package com.ssyt.wxstore.sys.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ssyt.wxstore.common.BaseDao;
import com.ssyt.wxstore.common.PageModel;
import com.ssyt.wxstore.common.util.MD5Util;
import com.ssyt.wxstore.sys.entity.SysUser;
import com.ssyt.wxstore.sys.entity.SysUserRole;

@Repository
public class UserDao extends BaseDao<SysUser, String> {

	/**
	 * 用户登录
	 * 
	 * @param code
	 * @param password
	 * @return
	 */
	public SysUser login(String code, String password) {
		return uniqueEntityBySql(
				"SELECT * FROM sys_user WHERE code=? AND password=? AND state=1",
				code, password);
	}

	/**
	 * 用户列表
	 * 
	 * @return
	 */
	public PageModel<SysUser> getUserList(int pageNo) {
		return pageEntityByHql(pageNo, 10, "FROM SysUser su");
	}

	/**
	 * 新增用户
	 * 
	 * @param roleId
	 * 
	 * @return
	 */
	public String add(SysUser user, List<String> roleId) {
		String password = user.getPassword();
		user.setPassword(MD5Util.toMD5(password));
		user.setState(1);
		String userId = save(user);
		List<SysUserRole> surList = new ArrayList<SysUserRole>();
		for (int i = 0; i < roleId.size(); i++) {
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setId(null);
			sysUserRole.setSysRoleId(roleId.get(i));
			sysUserRole.setSysUserId(userId);
			surList.add(sysUserRole);
		}
		user.setSysUserRoleList(surList);
		return userId;

	}

	public int update(SysUser user, List<String> roleId) {
		SysUser suser = get(user.getId());
		suser.setName(user.getName());
		update(suser);
		int row = updateByHql("DELETE SysUserRole WHERE sysUserId=?",
				user.getId());
		for (String rId : roleId) {
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setSysRoleId(rId);
			sysUserRole.setSysUserId(user.getId());
			getSession().save(sysUserRole);
		}
		return row;
	}

	public SysUser getUserRole(String id) {
		return uniqueEntityByHql("FROM SysUser WHERE id=?", id);
	}

}
